<template>
  <div :class="['zl-collapse', klCollapseClass]">
    <slot></slot>
  </div>
</template>

<script>
export default {
  name: 'klCollapse',
  props: {
    // 当前讲义的下标
    cIndex: {
      type: Number,
      default: -1
    },
    selectedSection: {
      type: String,
      default: ''
    },
    minHeight: {
      // 最小高度
      type: Number,
      default: 50
    },
    value: {
      type: Boolean,
      default: true
    },
    animate: {
      // 动画时间
      type: Number,
      default: 300
    }
  },
  data() {
    return {
      isInit: true,
      klCollapseClass: this.createId(),
      initHeight: 0
    }
  },
  watch: {
    selectedSection(val) {
      if (val === 'lecture' && this.isInit) {
        this.init()
      }
    },
    value(val) {
      this.handleHeight(val)
    }
  },
  methods: {
    // 初始化
    async init() {
      let { minHeight, cIndex, klCollapseClass } = this
      let el = document.querySelector(`.${klCollapseClass}`)
      if (!el) return
      // 每次初始化都需要先移除原来设置的高度
      el.removeAttribute('style')
      // 获取真实高度
      this.initHeight = el.offsetHeight
      if (this.initHeight <= minHeight) {
        this.$emit('min-updata', {
          cIndex
        })
      }
      await this.$nextTick()
      this.handleHeight(this.value, el)
    },
    async handleHeight(val, el) {
      let { minHeight, animate, klCollapseClass } = this
      if (!el) {
        el = document.querySelector(`.${klCollapseClass}`)
      }
      if (!el) return
      if (val) {
        el.style.height = this.initHeight + 'px'
        await this.sleep(animate)
        // 设置成auto是为了高度可以被拉升
        el.style.height = 'auto'
        return
      }
      el.removeAttribute('style')
      this.initHeight = el.offsetHeight
      el.style.height = this.initHeight + 'px'

      if (this.isInit) {
        el.style.height = minHeight + 'px'
        this.isInit = false
        await this.sleep(30)
        el.style.transition = `height ${animate}ms ease-in-out`
      } else {
        el.style.transition = `height ${animate}ms ease-in-out`
        await this.sleep(30)
        el.style.height = minHeight + 'px'
      }
    }
  }
}
</script>

<style scoped>
.zl-collapse {
  overflow: hidden;
}
</style>
